package com.hellloop.pim.alphabeat.network;

import java.io.*;
import java.net.*;

public class PIMClientHandler extends Thread {
	
	private PrintWriter writer;
	
	private BufferedReader reader;
	
	private Socket sock;
	
	private PIMServerMessageProcessor processor;
	
	private PIMServerConnectionThread serverThread;
	
	private int clientId;
	
	PIMClientHandler(PIMServerConnectionThread servThread, int clientId, Socket sock, PIMServerMessageProcessor processor) throws IOException{
	
		this.serverThread = servThread;
		this.sock = sock;
		this.writer = new PrintWriter(this.sock.getOutputStream(), true);
		this.reader = new BufferedReader(new InputStreamReader(this.sock.getInputStream()));
		// TODO Send message to the client, assigning the id to the client.
		this.processor = processor;
		this.clientId = clientId;
		this.start();
		
	}
	
	public void run(){
		while(true){
			try {
				receiveMessage();
			} catch (IOException e) {
				// Cannot read message from server
				e.printStackTrace();
				break;
			}
		}
	}
	
	void sendMessage(PIMMessage pm){
		String message = pm.toString();
		writer.println(message);
	}
	
	void receiveMessage() throws IOException{
		String line;
		if ((line = reader.readLine()) != null){
			processMessage( PIMMessage.decodeMessage(line) );
		}
	}
	
	void processMessage(PIMMessage msg){
		processor.processMessage(clientId, msg);
	}
	
	void closeConnection() throws IOException{
		this.writer.close();
		this.reader.close();
		this.sock.close();
	}
	
	public String toString(){
		return sock.toString();
	}
	
	public boolean equals(Object obj){
		
		if(this == obj)
			return true;
		
		if(obj instanceof PIMClientHandler){
			PIMClientHandler pimObj = (PIMClientHandler)obj;
			if(this.sock.equals(pimObj.sock))
				return true;
		}
			
		return false;
	}
	
	int getClientId(){
		return this.clientId;
	}

	void setClientId(int id){
		this.clientId = id;
	}
	
}
